<div>
  <div class="sub-navbar">
    <div class="container">
      <ul class="nav nav-pills">
        <li v-for="(index, item) in zones" v-bind:class="{active: item.active}">
          <a v-on:click="onSelectedZone(index)">{{item.value}}</a>
        </li>
      </ul>
    </div>
  </div>

  <div class="container">
    <div class="col-sm-2">
      <div class="list-group">
        <button href="#" class="list-group-item disabled">
          操作
        </button>
        <button class="btn list-group-item"
                v-on:click="onMenu"
                v-for="item in menus"
                v-bind:class="{'active': item.selected}"
                value="{{ item.key }}">
          <span v-if="item.enable">{{ item.value }}</span>
          <del v-else>{{ item.value }}</del>
        </button>
      </div>
    </div>

    <div class="col-sm-10">
      <div class="panel panel-default">
        <div class="panel-body">
          <button target="_blank" class="btn btn-primary btn-sm" role="button" v-on:click="createTopic">添加文章</button>
        </div>
      </div>
      <div class="panel panel-default">
        <div class="panel-heading">
        {{ pageTitle }}
        </div>
        <div class="panel-body">
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>作者</th>
                <th>标题</th>
                <th>Menu</th>
                <th>Submenu</th>
                <th>时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="topics.length > 0" v-for="(index, item) in topics">
                <td style="width: 80px">
                  <a href="<%= apiPrefix.page %>/user/{{ item.author.loginname}}?appId=<%= appId %>">{{item.author.loginname}}</a>
                </td>
                <td>
                  <a href='<%= apiPrefix.page %>/zone/{{selectedZone.key}}/{{selectedZone.template}}/topic/{{item._id}}/show?appId=<%= appId %>&zoneId={{selectedZone._id}}' target="_blank">{{item.title}}</a>
                </td>
                <td style="width: 80px">{{ item.menuValue }}</td>
                <td style="width: 80px">{{ item.submenuValue }}</td>
                <td style="width: 80px">{{ item.create_at_ago }}</td>
                <td style="width: 150px" class="opts">
                  <a class="active" v-if="item.top"><i class="fa fa-hand-o-up"></i></a>
                  <a v-else><i class="fa fa-hand-o-up"></i></a>
                  <a class="active" v-if="item.good"><i class="fa fa-star-o"></i></a>
                  <a v-else><i class="fa fa-star-o"></i></a>
                  <a class="active" v-if="item.lock"><i class="fa fa-lock"></i></a>
                  <a v-else><i class="fa fa-unlock"></i></a>
                  <a class="active" v-if="item.status"><i class="fa fa-eye"></i></a>
                  <a v-else><i class="fa fa-eye-slash"></i></a>
                </td>
                <td style="width: 80px">
                  <div class="btn-group disabled">
                    <button type="button" class="btn btn-default dropdown-toggle btn-sm" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                      操作 <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu disabled">
                      <li><a href='<%= apiPrefix.page %>/zone/{{selectedZone.key}}/{{selectedZone.template}}/topic/{{item._id}}/edit?appId=<%= appId %>&zoneId={{selectedZone._id}}' target="_blank">编辑</a></li>
                      <li class="divider"></li>
                      <li v-if="item.top"><a v-on:click="onTop(index, false)">取消置顶</a></li>
                      <li v-else><a v-on:click="onTop(index, true)">置顶</a></li>
                      <li v-if="item.good"><a v-on:click="onGood(index, false)">取消精华</a></li>
                      <li v-else><a v-on:click="onGood(index, true)">精华</a></li>
                      <li v-if="item.lock"><a v-on:click="onLock(index, false)">取消锁定</a></li>
                      <li v-else><a v-on:click="onLock(index, false)">锁定</a></li>
                      <li class="divider"></li>
                      <li><a v-on:click="onDelete(index)">删除</a></li>
                    </ul>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          <p v-show="topics.length < 1">无数据</p>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  var appId = $('[name=app-id]').val();
  var pagePrefix = '<%= apiPrefix.page %>';
  var dataPrefix = '<%= apiPrefix.data %>';
  var menusUtil = new MenusUtil(pagePrefix, dataPrefix);
  var vue = new Vue({
    el: '#app',
    data: {
      pageTitle: '全部',
      zones: [],
      selectedZone: '',
      menus: [],
      selectedMenuKey: 'all',
      topics: [],
      authors: [],
      submenus: [],
      currentPage: 1,
      pages: 1,
      canLoadData: true,
      errorMsg: '',
      successMsg: ''
    },
    methods: {
      getZones: function() {
        menusUtil.getZones(true, function(err, docs) {
          if (err) vue.errorMsg = err;
          else {
            docs.forEach(function(item) {
              item.active = false;
            });

            docs[0].active = true;

            vue.zones = docs;
            vue.selectedZone = vue.zones[0];
            vue.getMenus(0, vue.selectedZone._id);
          }
        });
      },
      onSelectedZone: function (index) {
        vue.zones.forEach(function(item) {
          item.active = false;
        });

        vue.currentPage = 1;
        vue.pages = 1;

        vue.zones[index].active = true;

        vue.selectedZone = vue.zones[index];
        vue.getMenus(index, vue.selectedZone._id)
      },
      getMenus: function(index, id) {
        menusUtil.getMenus({zoneId: id, all: true}, function(err, docs) {
          if (err) {
            vue.errorMsg = err;
          } else {
            console.log(vue.currentPage)
            vue.buildMenus(docs);
            vue.buildSubmenus(docs);
            vue.getData(vue.currentPage);
          }
        });
      },
      buildMenus: function(menus) {

        var menusTpl = [{key: 'all', value: '全部', enable: true, selected: false}, {key: 'good', value: '精选', selected: false}];

        menus.forEach(function(item) {
          item.selected = false;
          menusTpl.push(item);
        });

        vue.menus = menusTpl;
        vue.updateSelectedMenuKey(vue.menus[0].key);
      },
      buildSubmenus: function(menus) {
        vue.submenus = [];
        menus.forEach( function(item) {
          if (item.submenus) {
            item.submenus.forEach( function(submenu) {
              vue.submenus.push(submenu);
            });
          }
        });
      },
      onMenu: function(event) {
        vue.updateSelectedMenuKey(event.target.value);
        vue.currentPage = 1;
        vue.pages = 1;
        vue.topics = [];
        vue.getData(vue.currentPage);
      },
      getData: function(nextPage) {
        if (nextPage > vue.pages) return;

        $.post( dataPrefix + '/topics?',
          {appId: appId, zoneId: vue.selectedZone._id, menuKey: vue.selectedMenuKey, currentPage: nextPage, status: 'all'},
          function(result) {
            vue.canLoadData = true;

            if (result.err) {
              vue.errorMsg = result.err;
              return;
            }

            vue.authors = result.authors;
            vue.currentPage = result.currentPage;
            vue.pages = result.pages;
            vue.updateTopics(result.data);
        });
      },
      updateTopics: function(topics) {
        moment.locale('zh-cn')
        topics.forEach( function(item) {
          item.create_at_ago = moment(item.update_at).fromNow()
          var index1 = _.findIndex(vue.menus, function(menu) {
            return menu.key === item.menu;
          });

          if (index1 >= 0) {
            item.menuValue = vue.menus[index1].value;
          }

          var index2 = _.findIndex(vue.submenus, function(submenu) {
            return submenu.key === item.submenu;
          });

          if (index2 >=0 ) {
            item.submenuValue = vue.submenus[index2].value;
          }
        });

        topics.forEach( function(item) {
          var index = _.findIndex(vue.authors, function(i) {
            return i._id === item.author_id
          })

          if (index >= 0) {
            item.author = vue.authors[index]
          }
        })

        topics.forEach( function(item){
          vue.topics.push(item)
        });
      },
      updateSelectedMenuKey: function(key) {
        vue.menus.forEach(function(item) {
          if(item.key === key) {
            item.selected = true;
            vue.pageTitle = item.value;
          } else {
            item.selected = false;
          }
        });

        vue.selectedMenuKey = key;
      },
      onTop: function(index) {
        $.post( dataPrefix + '/topic/' + vue.topics[index]._id + '/top', {appId: appId, _csrf: $('#_csrf').val() }, function (result) {
          if (result.err) {
            vue.errorMsg = result.err;
          } else {
            vue.successMsg = result.msg;
            vue.topics[index].top = !vue.topics[index].top;
          }
        });
      },
      onGood: function(index) {
        $.post( dataPrefix + '/topic/' + vue.topics[index]._id + '/good', {appId: appId, _csrf: $('#_csrf').val() }, function (result) {
          if (result.err) {
            vue.errorMsg = result.err;
          } else {
            vue.successMsg = result.msg;
            vue.topics[index].good = !vue.topics[index].good;
          }
        });
      },
      onLock: function(index) {
        $.post( dataPrefix + '/topic/' + vue.topics[index]._id + '/lock', {appId: appId, _csrf: $('#_csrf').val() }, function (result) {
          if (result.err) {
            vue.errorMsg = result.err;
          } else {
            vue.successMsg = result.msg;
            vue.topics[index].lock = !vue.topics[index].lock;
          }
        });
      },
      onDelete: function(index) {
        if (confirm('确定要删除吗？')) {
          $.post( dataPrefix + '/topic/' + vue.topics[index]._id + '/delete', {appId: appId, _csrf: $('#_csrf').val() }, function (result) {
            if (result.err) {
              vue.errorMsg = result.err;
            } else {
              vue.topics.$remove(vue.topics[index]);
            }
          });
        }
      },
      onReviewed: function(index, topicId, status) {
        $.post( dataPrefix + '/topic/' + topicId + '/status', {appId: appId, status: status}, function (result) {
          if (result.err) {
            return vue.errorMsg = result.err;
          }
          vue.topics[index].status = status;
        });
      },
      createTopic: function () {
        location.href = '/topic/create?zoneId=' + vue.selectedZone._id
      }
    }
  });

  var scrollButtom = new ScrollButtom();
  scrollButtom.init(function() {
    if (vue.currentPage < vue.pages && vue.canLoadData) {
      vue.canLoadData = false;
      vue.getData(vue.currentPage + 1);
    }
  });

  vue.getZones();
</script>
